package com.twotwoshop.service.user.controller;

import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.common.enums.AppHttpCodeEnum;
import com.twotwoshop.util.AliOssUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

@RestController
@RequestMapping("/user/upload")//
@Slf4j
@RequiredArgsConstructor
public class UploadController {


    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;


    //最大文件内存
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

    private final AliOssUtil aliOssUtil;

    private final ExecutorService executorService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/file")
    public ResponseResult upload(@RequestParam("picUrl") MultipartFile file) {

        log.info("文件上传 :{}", file);

        if (file.getSize() > MAX_FILE_SIZE) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "图片大小不能超过10MB");
        }

        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;

            // 提交到线程池执行
            executorService.submit(() -> {
                try {
                    String filePath = aliOssUtil.upload(file.getBytes(), objectName);
                    log.info("文件上传成功，路径：{}", filePath);
                } catch (Exception e) {
                    log.error("文件上传失败：{}", e);
                }
            });

            //获取文件路径 先存到数据库中 异步将文件传入OSS
            String fileName = aliOssUtil.getFileName(objectName);
            return ResponseResult.okResult(fileName);

        } catch (Exception e) {
            log.error("文件上传失败：{}", e);
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
    }

}
